/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.gis.eemc.web;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import javax.faces.context.FacesContext;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.gis.eemc.domain.Faculty;
import net.gis.eemc.domain.Department;
import net.gis.eemc.service.FacultyServiceImpl;
import net.gis.eemc.service.DepartmentServiceImpl;

/**
 *
 * @author Sergey
 */
@ManagedBean(name = "departmentsBean")
@ViewScoped
public class DepartmentsBean {

    private final String allFaculties = "Все";
    List<Department> departments = null;
    private List<SelectItem> selectFaculties = null;
    private Map<Integer, Faculty> facultyMap = null;
    private FacultyServiceImpl facSrv = null;
    private DepartmentServiceImpl depSrv = null;
    private Integer selectedFaculty = 0;

    private synchronized void fillSelectFaculties() {
        selectFaculties = new ArrayList<SelectItem>();
        facultyMap = new HashMap<Integer, Faculty>();
        selectFaculties.add(new SelectItem(0, allFaculties));
        for (Faculty fac : facSrv.getFaculties()) {
            facultyMap.put(fac.getIdfaculty(), fac);
            selectFaculties.add(new SelectItem(fac.getIdfaculty(), fac.getShortName()));
        }
    }

    private synchronized void fillDepList() {
        if (selectedFaculty == null || selectedFaculty == 0) {
            departments = depSrv.getDepartments();
        } else {
            departments = depSrv.getDepartmentsForFaculty(selectedFaculty);
        }
    }

    /** Creates a new instance of DepartmentsBean */
    public DepartmentsBean() {
        try {
            facSrv = new FacultyServiceImpl();
            depSrv = new DepartmentServiceImpl();

            fillSelectFaculties();
            FacesContext context = FacesContext.getCurrentInstance();
            String id = context.getExternalContext().getRequestParameterMap().get("id");
            if (id != null) {
                selectedFaculty = new Integer(id);
            } else {
                selectedFaculty = 0;
            }

            fillDepList();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Department> getDepartments() {
        return departments;
    }

    public Integer getSelectedFaculty() {
        return selectedFaculty;
    }

    public void setSelectedFaculty(Integer faculty) {
        this.selectedFaculty = faculty;
        fillDepList();
    }

    public List<SelectItem> getSelectFaculties() {
        return selectFaculties;
    }
}
